package com.flowplan.auth.service;

import com.flowplan.auth.dto.LoginRequest;
import com.flowplan.auth.dto.LoginResponse;
import com.flowplan.auth.repository.SysUserRepository;
import com.flowplan.auth.util.JwtTokenUtil;
import com.flowplan.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 认证服务实现类
 * 
 * @author FlowPlan Team
 */
@Slf4j
@Service
public class AuthService {
    
    @Autowired
    private AuthenticationManager authenticationManager;
    
    @Autowired
    private SysUserRepository userRepository;
    
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    
    /**
     * 从Token中提取用户ID
     */
    public Long getUserIdFromToken(String token) {
        try {
            return jwtTokenUtil.getUserIdFromToken(token);
        } catch (Exception e) {
            log.error("从Token中提取用户ID失败: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 用户登录
     */
    @Transactional(readOnly = true)
    public LoginResponse login(LoginRequest loginRequest) {
        log.info("用户 {} 尝试登录", loginRequest.getUsername());
        
        // 注意：不要在生产环境中记录密码
        // log.info("用户 {} 面膜", loginRequest.getPassword());

        try {
            // 验证用户名密码
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.getUsername(),
                            loginRequest.getPassword())
            );
            
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            
            // 获取用户信息
            SysUser user = userRepository.findByUsername(loginRequest.getUsername())
                    .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
            
            // 生成Token
            String token = jwtTokenUtil.generateTokenWithUserId(user.getUsername(), user.getId());
            String refreshToken = jwtTokenUtil.generateRefreshToken(userDetails);
            
            // 构建响应
            LoginResponse.UserInfo userInfo = LoginResponse.UserInfo.builder()
                    .id(user.getId())
                    .username(user.getUsername())
                    .email(user.getEmail())
                    .role(user.getRole().getDescription())
                    .orgName(user.getOrg() != null ? user.getOrg().getOrgName() : null)
                    .avatarUrl(user.getAvatarUrl())
                    .build();
            
            LoginResponse response = LoginResponse.builder()
                    .token(token)
                    .refreshToken(refreshToken)
                    .tokenType("Bearer")
                    .expiresIn(86400L) // 24小时
                    .user(userInfo)
                    .build();
            
            log.info("用户 {} 登录成功", loginRequest.getUsername());
            return response;
            
            
        } catch (Exception e) {
            log.error("用户 {} 登录失败: {}", loginRequest.getUsername(), e.getMessage());
            throw new BadCredentialsException("用户名或密码错误");
        }
    }
    
    /**
     * 刷新Token
     */
    public LoginResponse refreshToken(String refreshToken) {
        try {
            if (!jwtTokenUtil.validateRefreshToken(refreshToken)) {
                throw new BadCredentialsException("刷新Token无效");
            }
            
            String username = jwtTokenUtil.getUsernameFromToken(refreshToken);
            SysUser user = userRepository.findByUsername(username)
                    .orElseThrow(() -> new UsernameNotFoundException("用户不存在"));
            
            if (!user.getIsActive()) {
                throw new BadCredentialsException("用户已被禁用");
            }
            
            // 生成新的访问Token
            String newToken = jwtTokenUtil.generateTokenWithUserId(user.getUsername(), user.getId());
            
            return LoginResponse.builder()
                    .token(newToken)
                    .refreshToken(refreshToken) // 刷新Token保持不变
                    .tokenType("Bearer")
                    .expiresIn(86400L)
                    .build();
            
        } catch (Exception e) {
            log.error("Token刷新失败: {}", e.getMessage());
            throw new BadCredentialsException("Token刷新失败");
        }
    }
    
    /**
     * 用户登出
     */
    public void logout(String token) {
        // 将Token加入黑名单（如果需要）
        log.info("用户登出");
    }
    
    /**
     * 验证Token
     */
    public boolean validateToken(String token) {
        try {
            String username = jwtTokenUtil.getUsernameFromToken(token);
            SysUser user = userRepository.findByUsername(username).orElse(null);
            return user != null && user.getIsActive() && !jwtTokenUtil.isTokenExpired(token);
        } catch (Exception e) {
            return false;
        }
    }
}